<template>
  <van-row>
    <van-nav-bar
      title="订单详情"
      left-text="返回"
      left-arrow
      @click-left="$emit('close')"
    >
      <template #right>
        <van-popover
          v-model="showPopover"
          placement="bottom-end"
          trigger="click"
          :actions="actions"
          @select="handleAction"
        >
          <template #reference>
            <van-icon name="ellipsis" size="20" />
          </template>
        </van-popover>
      </template>
    </van-nav-bar>
    <van-tabs v-model="active">
      <van-tab title="订单信息">
        <van-cell title="订单编号" :value="orderInfo.orderNo" />
        <van-cell value-class="cell_value" title="日期" :value="orderInfo.orderDate" />
        <van-cell value-class="cell_value" title="客户" :value="orderInfo.customerName" />
        <van-cell title="模具" :value="productInfo.moldName" />
        <van-cell value-class="cell_value" title="单价" :value="orderInfo.unitPrice">
          <template #default>
            {{ orderInfo.unitPrice }}元/{{ productInfo.unit }}
          </template>
        </van-cell>
        <van-cell value-class="cell_value" title="数量" :value="orderInfo.quantity">
          <template #default>
            {{ orderInfo.quantity }}{{ productInfo.unit }}
          </template>
        </van-cell>
        <van-cell value-class="cell_value" title="总价" :value="orderInfo.amount">
          <template #default>
            {{ orderInfo.amount }}元
          </template>
        </van-cell>
        <van-cell value-class="cell_value" title="订单状态">
          <template #default>
            <order-state-tag v-model="orderInfo.orderState" />
          </template>
        </van-cell>
        <van-cell value-class="cell_value" title="付款状态">
          <template #default>
            <payment-state-tag v-model="orderInfo.paymentState" />
          </template>
        </van-cell>
        <van-cell value-class="cell_value" title="付款金额" :value="orderInfo.paidAmount">
          <template #default>
            {{ orderInfo.paidAmount }}元
          </template>
        </van-cell>
        <van-cell value-class="cell_value" title="发货状态" :value="orderInfo.shipmentState">
          <template #default>
            <shipment-state-tag v-model="orderInfo.shipmentState" />
          </template>
        </van-cell>
        <van-cell value-class="cell_value" title="已发货数量" :value="orderInfo.shipmentQuantity">
          <template #default>
            {{ orderInfo.shippedQuantity }}{{ productInfo.unit }}
          </template>
        </van-cell>
        <van-cell title="备注" :value="orderInfo.remark" />
      </van-tab>
      <van-tab title="产品信息">
        <van-cell title="名称" :value="productInfo.moldName" />
        <van-cell title="颜色" :value="productInfo.color" />
        <van-cell title="材质" :value="productInfo.material" />
        <van-cell title="尺码" :value="productInfo.size" />
        <van-cell title="长度" :value="productInfo.length" />
      </van-tab>
      <van-tab title="排产信息">
        <div v-if="produceInfo">
          <van-cell title="排产单号" :value="produceInfo.produceNo" />
          <van-cell title="排产日期" value-class="cell_value" :value="produceInfo.produceDate" />
          <van-cell title="结束日期" :value="produceInfo.produceEndDate?produceInfo.produceEndDate:'未结束'" />
          <van-cell title="生产状态" :value="produceInfo.produceState">
            <template #default>
              <produce-state-tag v-model="produceInfo.produceState" />
            </template>
          </van-cell>
          <van-cell title="优先级" :value="produceInfo.priority">
            <template #default>
              <van-tag v-if="produceInfo.priority==='0'" type="success">普通</van-tag>
              <van-tag v-if="produceInfo.priority==='1'" type="danger">加急</van-tag>
            </template>
          </van-cell>
          <van-cell title="总数" :value="produceInfo.quantity">
            <template #default>
              {{ produceInfo.quantity }}{{ productInfo.unit }}
            </template>
          </van-cell>
          <van-cell title="余数" :value="produceInfo.remainingQuantity">
            <template #default>
              <span style="color: #ee0a24">
                {{ produceInfo.remainingQuantity }}{{ productInfo.unit }}
              </span>
            </template>
          </van-cell>
          <van-cell value-class="cell_value" title="生产进度">
            <template #default>
              <custom-progress v-model="produceInfo.percentage" />
            </template>
          </van-cell>
        </div>
        <van-empty v-else description="暂无排产信息" />
      </van-tab>
      <van-tab title="外发信息">
        <div v-if="outsourcedInfo">
          <van-cell title="供应商" :value="outsourcedInfo.supplierName" />
          <van-cell title="外发数量" :value="outsourcedInfo.quantity">
            <template #default>
              {{ outsourcedInfo.quantity }}{{ productInfo.unit }}
            </template>
          </van-cell>
          <van-cell title="外发单价">
            <template #default>
              {{ outsourcedInfo.unitPrice }}元/{{ productInfo.unit }}
            </template>
          </van-cell>
          <van-cell title="利润" :value="outsourcedInfo.profit">
            <template #default>
              {{ outsourcedInfo.profit }}元
            </template>
          </van-cell>
          <van-cell title="备注" :value="outsourcedInfo.remark" />
        </div>
        <van-empty v-else description="暂无外发信息" />
      </van-tab>
      <van-tab title="订单日志">
        <van-cell-group>
          <van-cell v-for="(item,index) in bizLogList" :key="index">
            <template #default>
              <div class="title">
                {{ item.username }}
              </div>
              <div class="right">
                {{ item.createTime }}
              </div>
              <div class="desc">
                {{ item.operationType }} {{ item.details }}
              </div>
            </template>
          </van-cell>
        </van-cell-group>
      </van-tab>
    </van-tabs>
    <van-popup v-model="showSubmit" position="right" :get-container="getContainer" :style="{ width: '100%', height: '100%' }">
      <order-submit-module ref="submitModule" @close="handleClose" />
    </van-popup>
    <van-popup v-model="showOs" position="right" :get-container="getContainer" :style="{ width: '100%', height: '100%' }">
      <os-submit-module ref="osSubmitModule" @close="handleClose" />
    </van-popup>
  </van-row>
</template>
<script>
import { cancelOrder, selectSaleOrderById, deleteSaleOrder, terminationOrder } from '@/api/saleOrder'
import { selectBizLogByBizId } from '@/api/bizLog'
import { Dialog, Toast } from 'vant'
import { produce } from '@/api/produce'
import OrderStateTag from '@/components/tag/OrderStateTag.vue'
import OrderSubmitModule from '@/views/order/submitModule.vue'
import OsSubmitModule from '@/views/order/osSubmitModule.vue'
import ProduceStateTag from '@/components/tag/ProduceStateTag.vue'
import CustomProgress from '@/components/CustomProgress.vue'
import PaymentStateTag from '@/components/tag/PaymentStateTag.vue'
import ShipmentStateTag from '@/components/tag/ShipmentStateTag.vue'

export default {
  name: 'OrderDetail',
  components: { ShipmentStateTag, PaymentStateTag, CustomProgress, ProduceStateTag, OsSubmitModule, OrderSubmitModule, OrderStateTag },
  data() {
    return {
      active: 0,
      orderInfo: {
        orderNo: '',
        customerName: ''
      },
      productInfo: {},
      produceInfo: {},
      outsourcedInfo: {},
      showPopover: false,
      showSubmit: false,
      showOs: false,
      actions: [
        { icon: 'records-o', text: '安排生产', action: 'produce', disabled: false },
        { icon: 'share-o', text: '订单外发', action: 'outsourced', disabled: false },
        { icon: 'edit', text: '修改订单', action: 'edit', disabled: false },
        { icon: 'cross', text: '取消订单', action: 'cancel', disabled: false },
        { icon: 'stop-circle-o', text: '终止订单', action: 'termination', disabled: false },
        { icon: 'delete-o', text: '删除订单', action: 'delete', disabled: false }],
      bizLogList: []
    }
  },
  methods: {
    init(id) {
      selectSaleOrderById(id).then(resp => {
        if (resp.success) {
          if (this.refreshing) {
            this.refreshing = false
          }
          this.orderInfo = resp.data
          this.productInfo = resp.data.productInfo
          this.produceInfo = resp.data.produceInfo
          this.outsourcedInfo = resp.data.outsourcedInfo
          this.setDisabled(this.orderInfo.orderState)
        }
      })
      this.setBizLog(id)
    },
    setBizLog(bizId) {
      const query = { bizId: bizId, tableName: 'erp_sale_order' }
      selectBizLogByBizId(query).then(resp => {
        if (resp.success) {
          this.bizLogList = resp.data
        }
      })
    },
    setDisabled(orderState) {
      for (let i = 0; i < this.actions.length; i++) {
        var action = this.actions[i]
        if (action.action === 'produce') {
          action.disabled = orderState !== '0'
        } else if (action.action === 'outsourced') {
          action.disabled = orderState !== '0'
        } else if (action.action === 'edit') {
          action.disabled = orderState !== '0' && orderState !== '1'
        } else if (action.action === 'delete') {
          action.disabled = orderState !== '0' && orderState !== '4'
        } else if (action.action === 'termination') {
          action.disabled = orderState !== '1'
        } else {
          action.disabled = ['0', '1', '2'].indexOf(orderState) === -1
        }
      }
    },
    handleAction(row) {
      if (row.action === 'cancel') {
        this.doCancel()
      } else if (row.action === 'outsourced') {
        this.doOutsourced()
      } else if (row.action === 'produce') {
        this.doProduce()
      } else if (row.action === 'delete') {
        this.doDelete()
      } else if (row.action === 'edit') {
        this.toEdit()
      } else if (row.action === 'termination') {
        this.doTermination()
      }
    },
    toEdit() {
      this.showSubmit = true
      this.$nextTick(() => {
        this.$refs.submitModule.init(this.orderInfo.id)
      })
    },
    doOutsourced() {
      this.showOs = true
      this.$nextTick(() => {
        this.$refs.osSubmitModule.init(this.orderInfo.id)
      })
    },
    doProduce() {
      Dialog.confirm({
        title: '生产确认',
        message: '是否安排生产'
      }).then(() => {
        const data = { ids: [this.orderInfo.id] }
        produce(data).then(resp => {
          if (resp.success) {
            Toast.success('安排生产成功')
            this.init(this.orderInfo.id)
          }
        })
      }).catch(() => {})
    },
    doDelete() {
      Dialog.confirm({
        title: '删除确认',
        message: '是否删除此订单'
      }).then(() => {
        const data = { ids: [this.orderInfo.id] }
        deleteSaleOrder(data).then(resp => {
          if (resp.success) {
            Toast.success('删除成功')
            this.$emit('close')
          }
        })
      }).catch(() => {})
    },
    doTermination() {
      Dialog.confirm({
        title: '终止确认',
        message: '是否终止此订单，终止订单后订单将变为已完成'
      }).then(() => {
        const data = { ids: [this.orderInfo.id] }
        terminationOrder(data).then(resp => {
          if (resp.success) {
            Toast.success('终止订单成功')
            this.init(this.orderInfo.id)
          }
        })
      }).catch(() => {})
    },
    doCancel() {
      let message
      if (this.orderInfo.orderState === '1') {
        message = '此订单已在生产中，是否取消此订单'
      } else {
        message = `客户名称：${this.orderInfo.customerName}，产品名称：${this.orderInfo.productName}，数量：${this.orderInfo.quantity}，是否取消此订单`
      }
      Dialog.confirm({
        title: '订单取消确认',
        message: message
      }).then(() => {
        cancelOrder(this.orderInfo.id).then(resp => {
          if (resp.success) {
            Toast.success('取消成功')
            this.init(this.orderInfo.id)
          }
        })
      }).catch(() => {})
    },
    handleClose() {
      this.showOs = false
      this.showSubmit = false
      this.init(this.orderInfo.id)
    },
    getContainer() {
      return document.body
    }
  }
}
</script>

<style scoped>

</style>
